package com.gitee.chili.leisure.message;

import cn.hutool.core.util.RandomUtil;
import com.gitee.chili.leisure.RoomManager;
import com.gitee.chili.leisure.core.AbstractDefaultMessage;
import com.gitee.chili.leisure.core.Packet;
import com.gitee.chili.leisure.game.MahjongPlayer;
import com.gitee.chili.leisure.game.Player;
import com.gitee.chili.leisure.game.RoomDetail;
import com.gitee.chili.leisure.model.MahjongModel;
import com.gitee.chili.leisure.util.AuxiliaryRoom;
import com.gitee.chili.leisure.util.Connection;
import com.gitee.chili.leisure.util.Enum;
import com.gitee.chili.leisure.util.TaskManager;
import com.google.protobuf.InvalidProtocolBufferException;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Objects;

/**
 * ExchangeCards
 *
 * @author week solider
 * @since 2020.09.19
 */
@Slf4j
public class ExchangeThree extends AbstractDefaultMessage {

    private Direction direction;

    public ExchangeThree(Packet packet, Channel channel) {
        super(packet, channel);
    }

    @Override
    protected void decoder(byte[] body) throws InvalidProtocolBufferException {
        MahjongModel.ExchangeThree exchangeCards = MahjongModel.ExchangeThree.parseFrom(body);

        Long roomNum = getRoomNum();

        RoomDetail roomDetail = RoomManager.obtain(roomNum);

        MahjongPlayer player = (MahjongPlayer) roomDetail.obtain(getMemberId());

        // 记录换牌信息
        player.setExchange(exchangeCards.getCardsList());
        // 移除丢弃的牌
        exchangeCards.getCardsList().forEach(c -> player.getHandsCards().removeIf(p -> p.equals(c)));

        // 停止定时任务
        TaskManager.remove(String.format(TaskManager.TaskNames.multiExchangeThree, roomNum.toString()), player.getUserId());

        // 推送消息给玩家 换牌中的手牌
        Connection.broadcaster().send(player.getRoomNum(), player.getUserId(), AuxiliaryRoom.pushExchangedData(player));

        List<? extends Player> players = roomDetail.getPlayers();

        // 还有牌友在换牌中 等待
        // 始终由最后一个牌友来决定换牌
        if (AuxiliaryRoom.exchangeOver(players)) {
            direction = Enum.valueOf(Direction.class, d -> d.ordinal() == RandomUtil.randomInt(3));

            // 随机换牌方向
            AuxiliaryRoom.exchangeThree(direction, players);
        }
    }

    @Override
    public Packet parseBody() {

        // 结束换三张
        AuxiliaryRoom.exchangeFinish(getRoomNum(), direction);

        // 由于是循环发送，所以已经在上面的方法中逐条执行，这里不需要返回任何数据
        return null;
    }

    /**
     * 换三张是否结束
     */
    public boolean isOver() {
        return Objects.nonNull(direction);
    }


    /**
     * 换牌方向
     */
    public enum Direction {

        /**
         * 上面
         */
        above,

        /**
         * 下面
         */
        below,

        /**
         * 对面
         */
        opposite
    }
}
